// Establish state to be used by remaining scripts.
var State = (function () {
    var collapse = function (delay, callback) {
        var timeout;
        return function () {
            var args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                callback.apply(undefined, arguments);
            }, delay);
        };
    };

    // Create TTR board and scorer.
    var board = new Board();
    var scorer = new TTRScorer(board, Data.players.length, 45);

    // Create KineticJS stage.
    var stageContainer = $("#stage-container");
    var stage = new Kinetic.Stage({
        "container": "stage-container",
        "width": stageContainer.width(),
        "height": stageContainer.height()
    });

    // Resize the KineticJS stage when the browser window resizes.
    $(window).resize(collapse(200, function () {
        var body = $(document.body),
            actualX = body.width() - 20,
            actualY = body.height() - 120,
            desiredX = 882,
            desiredY = 544;

        var actualRatio = actualX / actualY;
        var desiredRatio = desiredX / desiredY;

        var canvasX = Math.max(desiredX, (actualRatio > desiredRatio) ? (actualY * desiredRatio) : actualX);
        var canvasY = Math.max(desiredY, (actualRatio > desiredRatio) ? actualY : (actualX * Math.pow(desiredRatio, -1)));

        $("#board-container").add(stageContainer).width(canvasX).height(canvasY);

        stage.setWidth(canvasX);
        stage.setHeight(canvasY);
        stage.setScaleX(canvasX / desiredX);
        stage.setScaleY(canvasY / desiredY);
        stage.draw();
    }));
    $(window).resize();

    return {
        "scorer": scorer,
        "stage": stage,
        "cities": {},
        "tracks": []
    }
}());

var Events = {
    "track": {
        "clicked": new TypedEvent(),
        "tapped": new TypedEvent(),
        "entered": new TypedEvent(),
        "exited": new TypedEvent()
    },
    "reset": new TypedEvent()
};

(function () {
    // Wire reset button to fire reset event.
    $("#reset-button").on("click", function () {
        if (confirm("Reset game?")) {
            Events.reset.fire();
        }
    });

    // Reset the scorer instance on reset.
    Events.reset.on(function () {
        State.scorer.reset();
    });
}());
